import React, {useState} from "react";
import '../Style/Search.scss';
import {CloseCircleOutlined} from '@ant-design/icons';
import {serverMainPath} from '../Api/BaseUrl';
import axios from "../Api/api";

const Search = (props) =>{
    const [placeholderWord, setPlaceHolderWord] = useState('请输入笔记名称');
    const [inputValue,setInputValue] = useState('');
    const [noteLists,setNoteLists] = useState([]);
    const [flagList,setFlagList] = useState('none')
    const inputFocus = ()=>{
       setPlaceHolderWord('');
    }

    const inputTextChange = (e)=>{
        let text = e.target.value;
        setInputValue(text);
        setFlagList('block')
        if(inputValue.length >0 && inputValue.length !== 1){
            let username = JSON.parse(sessionStorage.getItem('userInfo')).username

            axios.get(serverMainPath.searchNotebook+inputValue+"/" + username).then(res=>{


                    setNoteLists(res.data)

            })
        }else if(inputValue.length   === 1){
            setNoteLists([]);
            setFlagList('none')
        }

    }
    const renderList = () =>{
        if(noteLists.length > 0 ){

            return noteLists.map((item, index) => {

                return (
                    <div key={index} className="noteBooks" onClick={() => {
                        props.clickEvent(item);
                        setFlagList('none');
                        setInputValue('')
                    }}>
                        <p>{item.notename}</p>
                    </div>
                )
            });
        }else{
            if(inputValue.length >0){
                return (<div className="noNoteBook" ><p>没有查找到笔记</p></div>)
            }

        }

    }

    const handleClickSearchList = (item)=>{
        props.clickEvent(item)

    }

    // const focusOut = () => {
    //     setPlaceHolderWord('请输入笔记名称')
    // }
    const handleClickClose = () => {
        setInputValue('');
        setFlagList('none')
    }

    return(
        <div className='search_body'>
            <input type="text" onFocus={inputFocus} value={inputValue} onChange={inputTextChange} placeholder={placeholderWord}/>
            <CloseCircleOutlined  style={{position:'absolute',top:17+"px",right:20+'px',cursor:'pointer'}} onClick={handleClickClose}/>
            <div className="s_lists" style={{display:flagList}} >
                {
                    renderList()
                }
            </div>
        </div>
    )
}

export default Search;